package com.net.utils;

import io.seata.core.context.RootContext;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * Htttp工具类
 *
 * @author tianyu.Ge
 * @date 2023/3/3 9:17
 */
public class HTTPUtil {

    public static final RestTemplate HTTP_UTIL() {
        RestTemplate restTemplate = SpringApplicationContextUtil.getBean(RestTemplate.class);
        return restTemplate;
    }

    /**
     * seata需要分布式事务专属方法
     *
     * @param url    请求路径
     * @param resultClass 返回类型
     * @return T
     * @author tianyu.Ge
     * @date 2023/3/3 9:29
     */
    public static <T> T get(String url, Class<T> resultClass) {
        HttpHeaders headers = new HttpHeaders();
        // 添加一些head设置,比如token等
        HttpEntity httpEntity = new HttpEntity(headers);
        ResponseEntity<T> exchange = HTTP_UTIL().exchange(url, HttpMethod.GET, httpEntity, resultClass);
        return exchange.getBody();
    }

    /**
     * seata需要分布式事务专属方法
     *
     * @param url    请求路径
     * @param params 请求参数
     * @param resultClass 返回类型
     * @return T
     * @author tianyu.Ge
     * @date 2023/3/3 9:29
     */
    public static <T> T seataGetFrom(String url, Map<String, Object> params, Class<T> resultClass) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add(RootContext.KEY_XID, RootContext.getXID());
        StringBuffer stringBuffer = new StringBuffer(url + "?");
        if (params != null && params.size() > 0) {
            params.forEach((k, v) -> {
                stringBuffer.append(String.format("&%s=%s", k, v));
            });
        }
        HttpEntity<String> httpEntity = new HttpEntity(headers);
        ResponseEntity<T> exchange = HTTP_UTIL().exchange(stringBuffer.toString(), HttpMethod.GET, httpEntity, resultClass);
        return exchange.getBody();
    }

}
